/**
 * Created by UYUES on 2016/5/23.
 */

//var baseUrl = "http://localhost:8080/OIEWPV2/";
//var baseUrl = "http://139.196.4.11:58086/";
//http://www.oiewp.com:58086/oiewp/
//var baseUrl = "http://www.oiewp.com:58086/oiewp/";
//var context = "https://dyjy.cccit.com.cn";
// var context = "http://192.168.3.104:8980/js";
// var context = "https://www.wxxf.net.cn/dyjy";
// var host = "https://www.wxxf.net.cn/minlo"
var src = "";
var fixParam={ts:new Date().getTime()};


/*
 * post请求
 * */
$.postAjax = function(url, param, fnCallback, fnErrorCallback) {
	//url = baseUrl + url;
	param = param || {};
	param = $.extend(param, fixParam);
	if (fnCallback && typeof fnCallback == "function") {
		$.post(url, param, function(json, status) {
					if (status == "success") {
						var data = JSON.parse(JSON.stringify(json));
						fnCallback(data);
					} else if (fnErrorCallback
							&& typeof fnErrorCallback == "function") {
						fnErrorCallback();
					}
		});
	}
};

/*get请求*/
$.getAjax = function(url, param, fnCallback, fnErrorCallback) {
	//url = baseUrl + url;
	param = param || {};
	param = $.extend(param, fixParam);
	if (fnCallback && typeof fnCallback == "function") {
		$.getJSON(url, param,
				function(json, status) {
					var data = JSON.parse(JSON.stringify(json));
					if (status == "success") {
						fnCallback(data);
					} else if (fnErrorCallback
							&& typeof fnErrorCallback == "function") {
						fnErrorCallback(data);
					}
				})
	}
};

/*get请求*/
$.getAjaxAsync = function(url, param, fnCallback, fnErrorCallback) {
	//url = baseUrl + url;
	param = param || {};
	param = $.extend(param, fixParam);
	if (fnCallback && typeof fnCallback == "function") {
	     $.ajaxSettings.async = false;  //设为同步请求
		$.getJSON(url, param,
				function(json, status) {
					var data = JSON.parse(JSON.stringify(json));
					if (status == "success") {
						fnCallback(data);
					} else if (fnErrorCallback
							&& typeof fnErrorCallback == "function") {
						fnErrorCallback(data);
					}
				})
				 $.ajaxSettings.async = true;  ///设为异步请求
	}
};



var util = {
       playVideo:function(elem) {

        var myFP = fluidPlayer(
            elem,
            {
                layoutControls: {
                    fillToContainer: true,
                    primaryColor: false,
                    posterImage: true,
                    autoPlay: true,
                    playButtonShowing: false,
                    playPauseAnimation: true,
                    mute: false,
                    logo: {
                        imageUrl: null,
                        position: 'top left',
                        clickUrl: null,
                        opacity: 1,
                        mouseOverImageUrl: null,
                        imageMargin: '2px',
                        hideWithControls: false,
                        showOverAds: false
                    },
                    htmlOnPauseBlock: {
                        html: null,
                        height: null,
                        width: null
                    },
                    allowDownload: false,
                    allowTheatre: false,
                    playbackRateEnabled: false,
                    controlBar: {
                        autoHide: false,
                        autoHideTimeout: 1,
                        animated: false
                    },
                },
                vastOptions: {}
            }
        );
    },
    formatNum: function(strNum) {
        if (strNum.length <= 3) {
            return strNum;
        }
        if ('!/(\+|-)?(\d+)(\.\d+)?$/.'.test(value)) {
            return strNum;
        }
        var a = RegExp.$1,
            b = RegExp.$2,
            c = RegExp.$3;
        var re = new RegExp();
        re.compile("(\\d)(\\d{3})(,|$)");
        while (re.test(b)) {
            b = b.replace(re, '$1,$2$3');
        }
        return a + "" + b + "" + c;
    },
	convertTime:function(key){
		key = key.replace(/\-/g, "/");  
		return key;
	}	
	,	
	getParam : function(key) {
		var search = window.location.search;
		if (!search)
			return "";
		var params = search.substring(1).split("&");
		for ( var index in params) {
			var param = params[index].split("=");
			if (param[0] == key)
				return param[1];
		}
		return "";
	},
	
	/**
	 * 生成一个指定范围的随机数
	 * 
	 * */
	getRandomNum:function(Min, Max) {
              const Range = Max - Min + 1;
              const Rand = Math.random();
              return Min + Math.floor(Rand * Range);
         },
     
	validateParam:function(params){
		var bool=true;
		 var datas=$.trim(params).split("&");
	     for(var i in datas){
	    	 var  data =datas[i];  
	         if(data.length < 1) {  
	           bool&=false; 
	         } else {  
	           bool&=true;  
	         }  
	     }
	   return bool;
	},
	/*
	 * 获取form序列化后的字段值
	 * */
	formParam : function(key) {
		var obj = {};
		var params = key.split("&");
		for ( var i in params) {
			var param = params[i].split("=");
			for ( var j in param) {
				obj[param[0]] = param[1];
			}
		}
		return obj;
	},
	
	
	/*
	 * 验证130-139,150-159,180-189号码段的手机号码
	 * */
	phoneValidation : function(ss) {
		var re;
		re = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
		if (re.test(ss)) {
			return true;
		} else {
			return false;
		}
	},
	
	
	/*
	 * 验证邮箱
	 * */
	emailValidation : function(ss) {
		var re;
		var re = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;//邮箱;
		if (re.test(ss)) {
			return true;
		} else {
			return false;
		}
	},
	
	/*
	 * 只能输入英文字母小数点苏子，和-
	 * 不能输入汉字
	 * */
	letterValidation : function(ss) {
		var re;
		re = /^[^\u4e00-\u9fa5]{0,}$/;
		if (re.test(ss)) {
			return true;
		} else {
			return false;
		}
	},
	

	/**
	 * 判断字符是否为空
	 */
	nullValidation:function(ss){
		var re;
		re =  /^$/;
		if(re.test(ss)){
			return true;
		}else{
			return false;
		}
	},

	/**
	 * 判断0-40个字符长度
	 */
	CharalenValidation:function(ss){
		var re;
		re = /[\u4e00-\u9fa5_a-zA-Z0-9_]{1,40}/;
		if(re.test(ss)){
			return true;
		}else{
			return false;
		}
	},
	
	
	
	/*
	 * 验证6-16位密码，只包含数字，大写字母，小写字母
	 * */
	passwordValidation : function(ss) {
		var re;
		re = /^[a-zA-Z0-9]{6,16}$/;
		if (re.test(ss)) {
			return true;
		} else {
			return false;
		}
	},
	/*
	 * 验证6位验证码，只包含0-9位数字
	 * */
	captchaValidation : function(ss) {
		var re;
		re = /^\d{6}$/;
		if (re.test(ss)) {
			return true;
		} else {
			return false;
		}
	}

}



/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
*/

function randomWord(randomFlag, min, max){
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if(randomFlag){
        range = Math.round(Math.random() * (max-min)) + min;
    }
    for(var i=0; i<range; i++){
        pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
    }
    return str;
}


/*
 生产
 *初始化全局缓存 初始化   初始化此书initialize  the global cache of navigator
 *
 *  初始化
 */

function initCache() {
	cache = window.localStorage
			|| {
				"setItem" : function(key, value) {
					this[key] = value;
				},
				"getItem" : function(key) {
					return this[key];
				},
				"removeItem" : function(key) {
					this[key] = null;
					delete this[key];
				},
				"clear" : function() {
					for ( var key in this) {
						if (key != 'setItem' && key != 'getItem'
								&& key != 'removeItem' && key != 'clear'
								&& key != 'setObjectItem'
								&& key != 'getObjectItem') {
							this[key] = null;
							delete this[key];
						}
					}
				}

			};

}
(initCache());





/**
 * Created by admin on 2015/9/9.
 */
/**
 *  使用方法 "aaa??".format("1","2") or aaa??".format("1").format("2");
 * @returns {*}
 */
String.prototype.format = function() {
	if (arguments && arguments.length) {
		var count = 0;
		var str = "";
		for (var index = 0; index < this.length; index++) {
			var code = this.charAt(index);
			switch (code) {
			case '?':
				str = str + arguments[count++];
				break;
			default:
				str = str + code;
				break;
			}
		}
		return str;
	}
	return this;
};


Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var number = this,
        negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};

/**
 * append  使用方法 "".append(...).append(...)
 * @returns {string}
 */
String.prototype.append = function() {
	var cur = "" + this;
	if (arguments) {
		for (var index = 0; index < arguments.length; index++) {
			cur = cur + arguments[index];
		}
	}
	return cur;
};


String.prototype.replaceAll = function(s1, s2) { 
    return this.replace(new RegExp(s1, "gm"), s2); 
    
}


function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data. At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}


//日期格式化
function formatDate(value,isdetails) {
    var date = new Date(value);
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 1);
    var day = date.getDate().toString();
    var hour = date.getHours().toString();
    var minutes = date.getMinutes().toString();
    var seconds = date.getSeconds().toString();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    if(isdetails==1){
        return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
    }
    return year + "-" + month + "-" + day ;
}



/**
 *  该提示依赖于easyui 的js 框架
 * */
 
function infoRemind(message){
	$.messager.alert("操作提示",message,"info");
}

function errorRemind(message){
	$.messager.alert("操作提示",message,"error");
}

function sysRemind(message){
	$.messager.show({
		title:'系统消息',
		msg:message,
		timeout:1000,
		showType:'slide'
	});
}


/**
 * EasyUI DataGrid根据字段动态合并单元格
 * 参数 tableID 要合并table的id
 * 参数 colList 要合并的列,用逗号分隔(例如："name,department,office");
 */
function mergeCellsByField(tableID, colList) {
    var ColArray = colList.split(",");
    var tTable = $("#" + tableID);
    var TableRowCnts = tTable.datagrid("getRows").length;
    var tmpA;
    var tmpB;
    var PerTxt = "";
    var CurTxt = "";
    var alertStr = "";
    for (j = ColArray.length - 1; j >= 0; j--) {
        PerTxt = "";
        tmpA = 1;
        tmpB = 0;

        for (i = 0; i <= TableRowCnts; i++) {
            if (i == TableRowCnts) {
                CurTxt = "";
            }
            else {
                CurTxt = tTable.datagrid("getRows")[i][ColArray[j]];
            }
            if (PerTxt == CurTxt) {
                tmpA += 1;
            }
            else {
                tmpB += tmpA;

                tTable.datagrid("mergeCells", {
                    index: i - tmpA,
                    field: ColArray[j],　　//合并字段
                    rowspan: tmpA,
                    colspan: null
                });
                tTable.datagrid("mergeCells", { //根据ColArray[j]进行合并
                    index: i - tmpA,
                    field: "Ideparture",
                    rowspan: tmpA,
                    colspan: null
                });

                tmpA = 1;
            }
            PerTxt = CurTxt;
        }
    }
}

function timeConvert(timestamp,num){//num:0 YYYY-MM-DD  num:1  YYYY-MM-DD hh:mm:ss // timestamp:时间戳
    timestamp = timestamp+'';
    timestamp = timestamp.length==10?timestamp*1000:timestamp;
    var date = new Date(timestamp);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    if(num==0){
        return y + '-' + m + '-' + d;
    }else{
        return y + '-' + m + '-' + d +' '+ h +':'+ minute +':' + second;
    }
}

/**
 *  该提示使用message.js 和message.css 的 配套 使用
 * type：success,info,warning,error,loading,close
 * text:是要 说明的 信息，
 * 如：CallOuts("error","login fail!")
 * */
function CallOuts(type,text){
	Qmsg[type](text);
}

/**
 * 读取友情链接
 */
function loadLinks(){
	setTimeout(function(){
		$.ajax({
			url:'/WxkjdsLink/w/list',
			data:{linkcate:'首页'},
			type:'get',
			success:function (res) {
				if (res.code == 1) {

					var datas=res.data;
					$(".nav1").empty();
					$(".nav2").empty();
					$.each(datas,function(index,item){
						var link='<li><a href="?">?</a></li>';
						link=link.format(item.linkurl,item.linkname);
						$(".nav1").append(link);
					});

				}else{
					CallOuts("error","友情链接请求失败，无法读取数据");
				}

			}
		});
	},1000);
}


function TrimStr(str, len) {

	//length属性读出来的汉字长度为1

	if(str.length*2 <= len) {
		return str;
	}

	var strlen = 0;
	var s = "";

	for(var i = 0;i < str.length; i++) {
		s = s + str.charAt(i);
		if (str.charCodeAt(i) > 128) {
			strlen = strlen + 2;
			if(strlen >= len){
				return s.substring(0,s.length-1) + "...";
			}

		} else {
			strlen = strlen + 1;
			if(strlen >= len){
				return s.substring(0,s.length-2) + "...";
			}
		}
	}
	return s;
}



			